package leecode.二分法;

public class 二分查找 {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        int[] nums = new int[]{0,2,3,4,5,6,9,11,25,166};
        Soulution soulution = new Soulution();
        int search = soulution.search(nums,11);
        System.out.println(search);
        long endTime = System.currentTimeMillis(); //获取结束时间
        System.out.println("程序运行时间： " + (endTime - startTime) + "ms");

    }

    static class Soulution{

        //相向指针遍历
        public int search (int[] nums,int target){
            int left=0,right=nums.length-1;

            while(true) {
                if (nums[left]==target){
                    return left;
                }else if( nums[right]==target){
                    return right;
                }
                if (right==left || right-left==1){
                    return -1;
                }
                left++;
                right--;
            }

        }


        //二分法查找
        public int search2 (int[] nums,int target){
            int left=0,right= nums.length-1;
            while (left<=right){
                int mid=(right-left)/2+left;
                int num=nums[mid];
                if (num==target){
                    return mid;
                }else if (num>target){
                    right=mid-1;
                }else {
                    left=mid+1;
                }
            }
            return -1;
        }
    }
}
